package win.lioil.bluetooth.util;

/**
 * Created by hejie on 18/6/26.
 */

public class ByteAndInt {

    /**
     * byte数组转int类型的对象
     * @return
     */
    public static int Byte2Int(byte[]bytes) {
        return (bytes[0]&0xff)
                | (bytes[1]&0xff)<<8
                | (bytes[2]&0xff)<<16
                | (bytes[3]&0xff)<<24;
    }
    public static int Byte22Int(byte[]bytes) {
        return (bytes[0]&0xff)
                | (bytes[1]&0xff)<<8;
    }

    /**
     * int转byte数组
     * @return
     */
    public static byte[] IntToByte(int num){
        byte[]bytes=new byte[4];
        bytes[0]=(byte) (num&0xff);
        bytes[1]=(byte) ((num>>8)&0xff);
        bytes[2]=(byte) ((num>>16)&0xff);
        bytes[3]=(byte) ((num>>24)&0xff);
        return bytes;
    }
    public static byte[] IntToByte2(int num){
        byte[]bytes=new byte[2];
        bytes[0]=(byte) (num&0xff);
        bytes[1]=(byte) ((num>>8)&0xff);
        return bytes;
    }
    /**
     * 字节数组转16进制
     * @param src
     * @return
     */
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }

        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if(str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for(int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }
}
